package net.apps123.fragment;

import android.graphics.Color;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.Toast;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import net.apps123.soundmeter.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

import cc.apk123.signalgen.FreqTextView;
import cc.apk123.signalgen.SeekBarListener;
import cc.apk123.signalgen.SignalGenActivity;
import cc.apk123.signalgen.Wave;
import cc.apk123.signalgen.task.GeneratorTask;
import cc.apk123.signalgen.task.PlayingTask;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShengChangFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShengChangFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private View rootView;
    private BarChart chart;

    public ShengChangFragment() {
        // Required empty public constructor
    }

    public static ShengChangFragment newInstance() {
        return new ShengChangFragment();
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShengChangFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShengChangFragment newInstance(String param1, String param2) {
        ShengChangFragment fragment = new ShengChangFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    private Button genSoundBtn;
    private static final String TAG = "MainActivity";
    private BlockingQueue<Short> blockingQueue = new LinkedBlockingDeque<>(10);
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    private int bufferSize = 512;
    private Button playButton;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_sheng_chang, container, false);
        chart = rootView.findViewById(R.id.bar_chart);

        final Wave wave = new Wave();
        wave.setWaveForm(Wave.TYPE_SINE);
        final FreqTextView freqNumber = (FreqTextView)rootView.findViewById(R.id.freqNumber);
        final SeekBar freqBar = (SeekBar) rootView.findViewById(R.id.freqBar);
        freqBar.setMax(Wave.MAX_FREQ);
        freqBar.setOnSeekBarChangeListener(new SeekBarListener(wave, freqNumber));
        freqBar.setProgress(0);
        freqBar.setProgress(500);

        // Listens for input on the frequency text box
//        freqNumber.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                if (event.getAction() == KeyEvent.ACTION_DOWN &&
//                        keyCode == KeyEvent.KEYCODE_ENTER){
//                    if (freqNumber.getParsedInt() != -1){
//                        freqBar.setProgress(freqNumber.getParsedInt());
//                    } else {
//                        Toast.makeText(getContext(),
//                                getResources().getString(R.string.invalid_input), Toast.LENGTH_LONG)
//                                .show();
//                    }
//                    return true;
//                }
//                return false;
//            }
//        });

        final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                Wave.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT, 2*bufferSize,
                AudioTrack.MODE_STREAM);


        // The generation and reproduction of samples is achieved using a producer-consumer pattern.
        // The first task is to generate the samples and store them in a queue
        final GeneratorTask generatorTask = new GeneratorTask(blockingQueue, wave);
        // The second task is to get samples from the queue and insert them into the audio buffer
        // in chunks of 512 samples, to be reproduced
        final PlayingTask playingTask = new PlayingTask(audioTrack, blockingQueue);



        genSoundBtn = rootView.findViewById(R.id.genSoundBtn);
        genSoundBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (generatorTask.isGenerating()) {
//                    generatorTask.stop();
//                    playButton.setText(R.string.play_button_text);
//                } else{
//                    executorService.execute(generatorTask);
//                    executorService.execute(playingTask);
////                    playButton.setText(R.string.stop_button_text);
//                }

                playWav(v);
            }
        });


        initBarChart();

        return rootView;
    }

    private MediaPlayer mediaPlayer;
    private void playWav(View view) {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(getActivity().getBaseContext(), Uri.parse("android.resource://"
                    + getActivity().getBaseContext().getPackageName() + "/" + R.raw.whie_noise_10s_48k));
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化柱状图控件
     */
    private void initBarChart(){
        // 如果图表中显示的条目超过60个，则不会显示任何值
        chart.setMaxVisibleValueCount(60);

        // 只能分别在x轴和y轴上进行缩放
        chart.setPinchZoom(false);

        // 阴影
        chart.setDrawBarShadow(false);
        // 是否绘制背景线
        chart.setDrawGridBackground(false);

        // x坐标绘制
        XAxis xAxis = chart.getXAxis();
        // x坐标位置
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        // x坐标线
        xAxis.setDrawGridLines(false);

        //Y轴左边第1条线
        chart.getAxisLeft().setDrawGridLines(false);


        // 添加一个漂亮平滑的动画
        chart.animateY(1500);

        // 是否绘制图例
        chart.getLegend().setEnabled(false);

        //设置数据
        setData();
    }


    protected String[] mMonths = new String[] {
            "1_1K", "1_4K", "2_1K", "2_4K", "3_1K", "3_4K", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
    };
    private void setData(){
        int count = 6;
        float range = 100;
        ArrayList<String> xVals = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            xVals.add(mMonths[i % 12]);
        }

        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        for (int i = 0; i < count; i++) {
            float mult = (range + 1);
            float val = (float) (Math.random() * mult);
            yVals1.add(new BarEntry(val, i));
        }

        BarDataSet set1;
        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet)chart.getData().getDataSetByIndex(0);
            set1.setYVals(yVals1);
            chart.getData().setXVals(xVals);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "DataSet");
            set1.setBarSpacePercent(35f);
            set1.setColors(ColorTemplate.MATERIAL_COLORS);

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(xVals, dataSets);
            data.setValueTextSize(10f);
//            data.setValueTypeface(mTf);

            chart.setData(data);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }


    }


}
